<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// ------------------------------------------------------------------------

class Ip
{

	private $_CI;

	 /**
     * 构造函数
     *
     * @access public
     * @return void
     */
    public function __construct()
    {
        /** 获取CI句柄 */
		$this->_CI = & get_instance();
    }

	function get_city_name_by_ip(){
		$ip=$this->_CI->input->server('HTTP_CLIENT_IP');
		if(!($this->_CI->input->server('HTTP_X_FORWARDED_FOR'))) {
			$ips=explode(",",$this->_CI->input->server('HTTP_X_FORWARDED_FOR'));
			if ($ip){
				array_unshift($ips,$ip);
				$ip=FALSE;
			}
			for($i=0;$i<count($ips);$i++){
				if (!preg_match("/^(10│172.16│192.168)./i",$ips[$i])){
					$ip=$ips[$i];
					break;
				}
			}
		}
		$ip=$ip?$ip:$this->_CI->input->server('REMOTE_ADDR');
//		$ip = '58.32.39.65';
		list($ip1,$ip2,$ip3,$ip4)=explode(".",$ip);
		$ip_val = $ip1*pow(256,3)+$ip2*pow(256,2)+$ip3*256+$ip4;

		$this->_CI->db->where('start <=', $ip_val);
		$this->_CI->db->order_by("start", "desc");
		$this->_CI->db->limit(1);
		$query = $this->_CI->db->get('ip');

		$row = $query->row_array();
		return $query->num_rows() ? $row['city'] : false;
	}

	function get_city_info_by_ip(){
		$city = $this->get_city_name_by_ip();
		if(!$city){
			return false;
		}

		$this->_CI->load->model('City_m','city');
		$ret['city_id'] = $this->_CI->city->get_id_by_city($city);
		$ret['city'] = $city;
		return $ret;
	}
}